/**
 *
 */
package com.honeybees.framework.spring.scheduler;

import java.text.ParseException;

import com.honeybees.framework.spring.util.BeanFactoryUtil;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;


/**
 * <dl>
 * <dt><b> Spring 4.x整合Quartz 2.x 动态修改定时器时间（修正多定时器SpringBean异常） </b></dt>
 * <p>
 * <dd>功能描述</dd>
 * </dl>
 * <p>
 * Copyright (C) All rights reserved.
 * </p>
 *
 * @author 李远明
 * @version 2016-01-08 11:47:57
 */
public abstract class AbstractScheduledJob {

    private static final Logger logger = LoggerFactory.getLogger(AbstractScheduledJob.class);

    protected String schedulerFactory;
    protected String triggerKey;

    public void setSchedulerFactory(String schedulerFactory) {
        Assert.notNull(schedulerFactory, "Scheduler factory can not be null");
        this.schedulerFactory = schedulerFactory;
    }

    public void setTriggerKey(String triggerKey) {
        Assert.notNull(triggerKey, "Trigger key can not be null");
        this.triggerKey = triggerKey;
    }

    /**
     * <dl>
     * <dt><b> 重置 CronExpression表达式 </b></dt>
     * <p>
     * <dd>功能描述</dd>
     * </dl>
     *
     * @param cronExpression CronExpression表达式
     * @author 李远明
     * @version 2016-01-08 11:50:18
     */
    protected void resetScheduledJob(String cronExpression) {
        // Scheduler schedulerFactory = (Scheduler) getObject(this.schedulerFactory);
        // CronTriggerImpl cronTrigger = (CronTriggerImpl) getObject(this.triggerKey);

        Scheduler schedulerFactory = BeanFactoryUtil.getBean(this.schedulerFactory, Scheduler.class);
        CronTriggerImpl cronTrigger = BeanFactoryUtil.getBean(this.triggerKey, CronTriggerImpl.class);

        String originCronExpression = cronTrigger.getCronExpression();
        if (!originCronExpression.equalsIgnoreCase(cronExpression)) {
            try {
                cronTrigger.setCronExpression(cronExpression);
            } catch (ParseException e) {
                logger.error("解析CronExpression表达式异常，请检查CronExpression表达式", e);
            }
            try {
                schedulerFactory.rescheduleJob(cronTrigger.getKey(), cronTrigger);
                logger.debug("resetScheduledJob completed.");
            } catch (SchedulerException e) {
                logger.error("rescheduleJob error", e);
            }
        }
    }

    /**
     * <dl>
     * <dt><b> 定时任务处理逻辑 </b></dt>
     * <p>
     * <dd>功能描述</dd>
     * </dl>
     *
     * @author 李远明
     * @version 2016-01-08 11:50:18
     */
    public abstract void doScheduledJob();

}
